package com.sailing.xjpb.common.thread;

import com.google.common.collect.Lists;
import lombok.Data;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.function.Supplier;
import java.util.stream.Collectors;

/**
 * 任务执行器
 *
 * @param <T> 任务执行完成返回结果类型
 * @deprecated 在最新技术栈jdk8上，存在执行异步任务卡死情况，建议先试用{@link TaskRunnerV1} 替代
 */
@Data
@Deprecated
public final class TaskRunner<T> {

    private final List<CompletableFuture<T>> taskList;

    private final Executor threadPools;

    public TaskRunner(Executor threadPools) {
        this.threadPools = threadPools;
        this.taskList = Lists.newLinkedList();
    }

    public void doExecute(Supplier<T> supplier) {
        CompletableFuture<T> completableFuture = CompletableFuture.supplyAsync(supplier, threadPools);
        taskList.add(completableFuture);
    }

    public List<T> collect() {
        return taskList.stream().map(CompletableFuture::join).collect(Collectors.toList());
    }

}
